package com.diy.sigmund.diycommon.test.spring.config.apollo;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ylm-sigmund
 * @since 2021/10/29 20:53
 */
@Component
public class ZuulPropertiesRefresher implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(ZuulPropertiesRefresher.class);

    private ApplicationContext applicationContext;

    @Autowired
    private SampleZuulConfig sampleZuulConfig;

    @ApolloConfigChangeListener(value = {"application", "FX.apollo", "application.yml"},
            interestedKeyPrefixes = "test.zuul.")
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshZuulProperties(changeEvent);
    }

    private void refreshZuulProperties(ConfigChangeEvent changeEvent) {
        log.info("Refreshing zuul properties!");
        log.info("sampleZuulConfig = {}", JacksonUtil.toJson(sampleZuulConfig));
        /**
         * rebind configuration beans, e.g. ZuulProperties
         * @see org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder#onApplicationEvent
         */
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

        /**
         * refresh routes
         * @see org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration.ZuulRefreshListener#onApplicationEvent
         */
        // this.applicationContext.publishEvent(new RoutesRefreshedEvent(routeLocator));

        log.info("Zuul properties refreshed!");
        log.info("sampleZuulConfig = {}", JacksonUtil.toJson(sampleZuulConfig));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
